package com.wiscamp.ninechapters.problems.infrastructure.mappers.tasks;

import com.wiscamp.ninechapters.problems.infrastructure.po.tasks.TaskPO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * 习题集分发任务仓储对象
 *
 * @author yifeng
 */
@Repository
public interface TaskMapper extends JpaRepository<TaskPO, Long>, JpaSpecificationExecutor<TaskPO> {

    @Modifying
    @Transactional
    @Query("delete from TaskPO e where e.assignmentId = :assignmentId and e.setId = :setId and e.taskStatusId = :taskStatusId and e.userId in (:userIds)")
    void removeUserTasksByStatus(long assignmentId, long setId, int taskStatusId, Collection<Long> userIds);


    @Modifying
    @Transactional
    @Query(nativeQuery = true, value = "update tasks set task_status_id = :targetStatus \n" +
            "where task_id in (select temp.task_id from (select t.task_id from tasks_view t, assignments a\n" +
            "where a.id = t.assignment_id and t.task_status_id = :sourceStatus\n" +
            "and a.assignment_time BETWEEN :startDate and :endDate) temp)")
    void updateTasksStatus(int sourceStatus, int targetStatus, String startDate, String endDate);


}